import requests
import re
import time
import json
from somecookie import readCookie,writeCookies


headers = {
    'authority': 'passport.weibo.com',
    'accept': '*/*',
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'cache-control': 'no-cache',
    # Requests sorts cookies= alphabetically
    # 'cookie': 'tid=6z+i0zLCtxM9hN+ozl1Z4Cd14bfqkcAg/gKvm6sexGE=__095; SRT=D.QqHBTrsPP4uaOdRtOeYoWr9NUdSqdGbQQ-uYddouW-WwMdbbN-bmAqMRNbHi5mYNUCsuPDbgVdsqMeMNAZSAK4MtNQ9nJ%21YudDBN5ESC5eMgA-iAWEHpPcbgUev-TX77%2AB.vAflW-P9Rc0lR-ykKDvnJqiQVbiRVPBtS%21r3J8sQVqbgVdWiMZ4siOzu4DbmKPWFSDPSSNunAcbc5bE-UQijVOWBJDW8; SRF=1661751547; PC_TOKEN=cca9fe5df5',
    'pragma': 'no-cache',
    'referer': 'https://passport.weibo.com/visitor/visitor?entry=miniblog&a=enter&url=https%3A%2F%2Fweibo.com%2F&domain=.weibo.com&ua=php-sso_sdk_client-0.6.36&_rand=1661752056.8322',
    'sec-ch-ua': '"Chromium";v="104", " Not A;Brand";v="99", "Google Chrome";v="104"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'script',
    'sec-fetch-mode': 'no-cors',
    'sec-fetch-site': 'same-origin',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36',
}


# 获取登入时要用的cookie
def getHeader():
    cookies = {
        'tid': '6z+i0zLCtxM9hN+ozl1Z4Cd14bfqkcAg/gKvm6sexGE=__095',
        'SRT': 'D.QqHBTrsPP4uaOdRtOeYoWr9NUdSqdGbQQ-uYddouW-WwMdbbN-bmAqMRNbHi5mYNUCsuPDbgVdsqMeMNAZSAK4MtNQ9nJ%21YudDBN5ESC5eMgA-iAWEHpPcbgUev-TX77%2AB.vAflW-P9Rc0lR-ykKDvnJqiQVbiRVPBtS%21r3J8sQVqbgVdWiMZ4siOzu4DbmKPWFSDPSSNunAcbc5bE-UQijVOWBJDW8',
        'SRF': '1661751547',
        'PC_TOKEN': 'cca9fe5df5',
    }
    params = {
        'a': 'restore',
        'cb': 'restore_back',
        'from': 'weibo',
        '_rand': '0.20302263308566282',
    }
    url = 'https://passport.weibo.com/visitor/visitor'
    response = requests.get(url, params=params, cookies=cookies, headers=headers)
    cookie = response.cookies
    cookies = {
        'PC_TOKEN': 'cca9fe5df5',
        'SUB': cookie._find('SUB'),
        'SRT': cookie._find('SRT'),
        'SRF': cookie._find('SRF'),
        'SUBP': cookie._find('SUBP')
    }
    print(cookies)
    return cookies


def getQrcode():
    params = {
        'entry': 'sinawap',
        'size': '180',
        'callback': 'STK_16617521005561',
    }
    url = 'https://login.sina.com.cn/sso/qrcode/image'
    response = requests.get(url, params=params, headers=headers)
    text = response.text
    res = re.search('STK_16617521005561\((.*)\)', text).groups()[0]
    data = (json.loads(res))['data']
    print(data)  # 二维码地址
    return data['qrid']

def getAlt(qrid):
    url = 'https://login.sina.com.cn/sso/qrcode/check?entry=sinawap&qrid=' + qrid + '&callback=STK_16613923043941'
    r = requests.get(url)
    r.raise_for_status()
    return r.text



def getTicket(alt):
    params = {
        'entry': 'sinawap',
        'returntype': 'TEXT',
        'crossdomain': '1',
        'cdult': '3',
        'domain': 'weibo.com',
        'alt': alt,
        'savestate': '30',
        'callback': 'STK_16613923043941',
    }
    response = requests.get('https://login.sina.com.cn/sso/login.php', params=params, headers=headers)

    SUB = response.cookies._find('SUB')
    writeCookies('SUB1',SUB)
    cookie_keys=['tgc','SUBP','ALC','ALF','LT']
    for key in cookie_keys:
        writeCookies(key,response.cookies._find(key))
    text = response.text
    url = eval(re.search('STK_16613923043941\((.*)\)', text).groups()[0])['crossDomainUrlList'][0].replace('\\', '')
    print(url)
    return url
    # STK_16613923043941({"retcode":"0","uid":"7575693963","nick":"\u5927\u4fa0\u725b\u6709\u5fb7",
    #                     "crossDomainUrlList":["https:\/\/passport.weibo.com\/wbsso\/login?ticket=ST-NzU3NTY5Mzk2Mw%3D%3D-1661763403-gz-B65D9D9FA4802246141D189A30F3CC89-1&ssosavestate=1693299403"]});


def getOnlodad(url, cookies):
    params = {
        'action': 'login',
        'callback': 'STK_166175492204831',
    }
    response = requests.get(url, params=params, cookies=cookies, headers=headers)
    ke=['SUBP','SUB','SRT','SRF']
    for k in ke:
        writeCookies(k,response.cookies._find(k))
    if (response.cookies._find('SUB')):
        print(response.cookies._find('SUB'))
    print("####################################################################")
    return 'success'


 # qrid = request.GET.get("qrid")
 #    data = load.getAlt(qrid)
 #    res = eval(re.search('STK_16613923043941\((.*)\)', data).groups()[0].replace('null','0'))
 #    if res['msg']=='succ':
 #        alt = res['data']['alt']
 #        print(alt)
 #        url = load.getTicket(alt)
 #        cookies = load.getHeader()
 #        res=load.getOnlodad(url, cookies)
 #        return HttpResponse(json.dumps("success"))
 #    else:
 #        return HttpResponse(json.dumps("wait"))


def main():
    qrid = getQrcode()
    while(1):
        time.sleep(3)
        data = getAlt(qrid)
        print(data)
        res = eval(re.search('STK_16613923043941\((.*)\)', data).groups()[0].replace('null','0'))
        if res['msg']=='succ':
            alt = res['data']['alt']
            url = getTicket(alt)
            cookies = getHeader()
            res=getOnlodad(url, cookies)
            break



main()
